package com.boot.app.development.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.boot.app.development.domain.DevelopmentDemoAddition;
import com.boot.app.development.dto.DemoDto;
import com.boot.app.development.mapper.DevelopmentDemoMapper;
import com.boot.app.development.domain.DevelopmentDemo;
import com.boot.app.development.service.IDevelopmentDemoAdditionService;
import com.boot.app.development.service.IDevelopmentDemoService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class DevelopmentDemoServiceImpl extends ServiceImpl<DevelopmentDemoMapper, DevelopmentDemo> implements IDevelopmentDemoService {

    @Autowired
    private DevelopmentDemoMapper developmentDemoMapper;

    @Autowired
    private IDevelopmentDemoAdditionService demoAdditionService;

    @Override
    public DemoDto getDemoDtoById(long id) {
        DemoDto demoDto = new DemoDto();

        DevelopmentDemo developmentDemo = developmentDemoMapper.selectById(id);

        LambdaQueryWrapper<DevelopmentDemoAddition> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(DevelopmentDemoAddition::getDemoId, id);
        DevelopmentDemoAddition developmentDemoAddition = demoAdditionService.getOne(queryWrapper);

        BeanUtils.copyProperties(developmentDemo, demoDto);
        BeanUtils.copyProperties(developmentDemoAddition, demoDto);
        return demoDto;
    }

    @Override
    public Page<DemoDto> pageDemoDto(Page<DemoDto> demoDtoPage, DemoDto demoDto) {
        return developmentDemoMapper.selectDemoDtoPage(demoDtoPage, demoDto);
    }

    @Transactional
    @Override
    public boolean saveOrUpdateDemoDto(DemoDto demoDto) {
        DevelopmentDemo developmentDemo = new DevelopmentDemo();
        DevelopmentDemoAddition developmentDemoAddition = new DevelopmentDemoAddition();

        BeanUtils.copyProperties(demoDto, developmentDemo);
        super.saveOrUpdate(developmentDemo);

        BeanUtils.copyProperties(demoDto, developmentDemoAddition);
        developmentDemoAddition.setDemoId(developmentDemo.getId());
        demoAdditionService.saveOrUpdate(developmentDemoAddition);
        return true;
    }

    @Transactional
    @Override
    public boolean removeDemoDtoById(long id) {
        developmentDemoMapper.deleteById(id);
        demoAdditionService.removeById(id);
        return true;
    }
}
